package com.weishi.project.training.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.training.domain.Sportsman;
import com.weishi.project.training.service.ISportsmanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.weishi.project.training.mapper.RaceDataMapper;
import com.weishi.project.training.domain.RaceData;
import com.weishi.project.training.service.IRaceDataService;

/**
 * 赛后数据表Service业务层处理
 */
@Service
public class RaceDataServiceImpl extends ServiceImpl<RaceDataMapper, RaceData> implements IRaceDataService {

    @Autowired
    private RaceDataMapper raceDataMapper;

    /**
     * 运动员表接口
     */
    @Autowired
    private ISportsmanService sportsmanService;



    /**
     * 查询列表
     */
    @Override
    public List<RaceData> selectRaceDataList(RaceData raceData) {
        return raceDataMapper.selectRaceDataList(raceData);
    }



    /**
     * 教练员端 -- 新增赛后数据
     */
    @Override
    public AjaxResult addRaceData(JSONObject jsonObject) {
        // 查询运动员详情
        Sportsman sportsman = sportsmanService.getById(Integer.parseInt(jsonObject.get("sportsmanId").toString()));

        // 查询前端发送的 list 数据
        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<RaceData> raceDataList = JSON.parseArray(jsonArray.toString(), RaceData.class);
        if(raceDataList.size() > 0){
            raceDataList.forEach( p-> {
                RaceData raceData = new RaceData();
                StringUtils.copyProperties(p , raceData);
                raceData.setSportsmanId(sportsman.getId());
                raceData.setSportsmanName(sportsman.getName());
                raceData.setSportsmanSex(sportsman.getSex());
                raceData.setCtime(new Date());
                raceData.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                raceData.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                save(raceData);
            });
        }
        return AjaxResult.success();
    }



    /**
     * 教练员端 -- 查询赛后数据
     */
    @Override
    public AjaxResult getRaceData(RaceData raceData) {
        return AjaxResult.success(Optional.ofNullable(list(Wrappers.<RaceData>lambdaQuery()
                .eq(RaceData::getSportsmanId , raceData.getSportsmanId())
                .eq(RaceData::getTrainingDayId , raceData.getTrainingDayId())
                .eq(RaceData::getGroupId , raceData.getGroupId())
                .orderByDesc(RaceData::getCtime))));
    }















}